/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 
 * @author JAD!
 */
public class Client implements java.lang.Runnable {
	java.net.Socket sock = null;
	String host;
	int port;
	Long time = System.currentTimeMillis();
	String name = "";

	public Client(String host, int port) {
		super();
		this.host = host;
		this.port = port;
	}

	public int connect()// String host,int port)
	{

		try {
			sock = new java.net.Socket(host, port);
		} catch (UnknownHostException ex) {
			System.out
					.println("Не могу подключится к данному IP,или IP введен неверно.");
			return -1;
		} catch (IOException ex) {
			System.out.println("Ошибка соединения");
			return -1;
		}

		return 0;
	}

	public void run() {
		while (true) {
			java.lang.Thread.yield();
			if (connect() == 0) {
				System.out.println("Server avaible!");

				java.io.PrintWriter out = null;
				java.io.BufferedReader in = null;

				try {

					// out = new
					// java.io.PrintWriter(sock.getOutputStream(),true);
					in = new java.io.BufferedReader(
							new java.io.InputStreamReader(sock.getInputStream()));
					out = new java.io.PrintWriter(new java.io.BufferedWriter(
							new java.io.OutputStreamWriter(sock
									.getOutputStream())), true);
				} catch (IOException ex) {
					Logger.getLogger(Client.class.getName()).log(Level.SEVERE,
							null, ex);
				}

				try {
					String st = "";
					out.println("name?");
					st = in.readLine();
					name = st;
					// out.println(String.valueOf(System.currentTimeMillis()));
					// out.println("END");
					boolean b = true;
					while (b) {

						if (in.ready()) {
							st = in.readLine();
							if (st != null)
								if (st.equals("END")
										|| System.currentTimeMillis() - time > 7000)
									b = false;
						} else
							try {
								out.println(String.valueOf(System
										.currentTimeMillis()));
								System.out.println("Client " + name
										+ " geted data from server:" + st);
								time = System.currentTimeMillis();
								Thread.currentThread().sleep(2000);
							} catch (InterruptedException ex) {
								finalize();
							}
					}

				} catch (IOException ex) {
					finalize();
				}

				finalize();

				/*
				 * try { sock.close(); } catch (IOException ex) {
				 * Logger.getLogger(Client.class.getName()).log(Level.SEVERE,
				 * null, ex); } } try { Thread.currentThread().sleep(2000); }
				 * catch (InterruptedException ex) {
				 * Logger.getLogger(Client.class.getName()).log(Level.SEVERE,
				 * null, ex); }
				 */}
		}
	}

	@Override
	protected void finalize() {
		try {
			System.out.println("Client " + name + "thread auto deleted.");
			sock.close();
			Thread.currentThread().stop();
		} catch (IOException ex) {
			Logger.getLogger(Client.class.getName())
					.log(Level.SEVERE, null, ex);
		}
	}
}
